﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Web.Mvc;
using Vit.Mvc.Validation;

namespace Vit.Mvc.Extensions
{
    public static class ModelStateDictionaryExtension
    {
        public static void AddModelErrors(this ModelStateDictionary modelStateDictionary, ValidationStateDictionary validationStateDictionary)
        {
            foreach (KeyValuePair<Type, ValidationState> validationState in validationStateDictionary)
            {
                foreach (ValidationError validationError in validationState.Value.Errors)
                {
                    string modelProperty = validationError.Name.Split('.')[0];
                    string key = modelProperty; // string.Format("{0}.{1}", validationState.Key.Name, modelProperty);

                    modelStateDictionary.AddModelError(key, validationError.Message);

                    modelStateDictionary.SetModelValue(
                        key,
                        new ValueProviderResult(
                            validationError.AttemptedValue,
                            validationError.AttemptedValue as string,
                            CultureInfo.CurrentCulture
                            )
                        );
                }
            }
        }
    }
}
